package com.lsy.weizhi2.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.LoginObject;
import com.lsy.weizhi2.activity.HomePage;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.myutils.FragmentCall;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;
import com.tencent.connect.UserInfo;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import com.lsy.weizhi2.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 嗨哟 on 2016/12/6.
 */
public class LoginFragment extends Fragment {
    private View view,login_password_line,login_phone_line;
    private EditText login_phone_et,login_password_et;
    private ImageView login_phone_iv,login_password_iv,login_qq,login_weixin,login_weibo;
    private Button login_btn;
    private Context context;
    private Gson gson=new Gson();
    //private Tencent mTencent;//腾讯的实例
    //private BaseUiListener qqLoginListtenr;//腾讯的回调接口
    private String openID;//QQ登录的唯一身份标识
    private Bundle bundle;//存放QQ登录的个人信息
    private FragmentCall fragmentCall;
    // IWXAPI 是第三方app和微信通信的openapi接口
    public static IWXAPI api;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //此处程序不走？
        Log.i("fragment","attach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentCall= (FragmentCall) getActivity();
        Log.i("fragment","create");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_login,container,false);
        login_phone_et= (EditText) view.findViewById(R.id.login_phone_et);
        login_password_et= (EditText) view.findViewById(R.id.login_password_et);
        login_phone_iv= (ImageView) view.findViewById(R.id.login_phone_iv);
        login_password_iv= (ImageView) view.findViewById(R.id.login_password_iv);
        login_phone_line=view.findViewById(R.id.login_phone_line);
        login_password_line=view.findViewById(R.id.login_password_line);
        login_btn= (Button) view.findViewById(R.id.login_btn);
        login_qq= (ImageView) view.findViewById(R.id.login_qq);
        login_weixin= (ImageView) view.findViewById(R.id.login_weixin);
        login_weibo= (ImageView) view.findViewById(R.id.login_weibo);
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String user_phone=login_phone_et.getText().toString();
                String password=login_password_et.getText().toString();
                if(TextUtils.isEmpty(user_phone)){
                    MyMethod.showToast(context,"请输入用户名");
                }else if(TextUtils.isEmpty(password)){
                    MyMethod.showToast(context,"请输入密码");
                }else{
                    LoginAccount(user_phone,password);
                }
            }
        });
        login_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentCall.Select(1);
            }
        });
        login_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentCall.Select(1);
            }
        });
        login_weibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentCall.Select(1);
            }
        });
        //监听焦点变化
        login_phone_et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    Log.i("message","Cursor==="+ login_phone_et.hasFocus()+"\n"+login_password_et.hasFocus());
                    login_phone_iv.setImageResource(R.mipmap.login_ico1_03);
                    login_phone_line.setBackgroundResource(R.color.clicked_ok);
                    login_password_iv.setImageResource(R.mipmap.login_ico2_08);
                    login_password_line.setBackgroundResource(R.color.clicked_no);
                }else{
                    login_phone_iv.setImageResource(R.mipmap.login_ico2_03);
                    login_phone_line.setBackgroundResource(R.color.clicked_no);
                    login_password_iv.setImageResource(R.mipmap.login_ico1_08);
                    login_password_line.setBackgroundResource(R.color.clicked_ok);
                }
            }
        });
        return view;
    }

    private void LoginAccount(String username,String password){
        Map<String,String> map=new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        MyOkHttpUtils.getInstance(context).doPostLogin(Constants.USER_LOGIN,map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {
                        Log.i("LoginFragment","message=f=="+message);
                        MyMethod.ShowDialog(context,message);
                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("LoginFragment","message=s=="+message);
                        if(message!=null){
                            try {
                                JSONObject jsonobject=new JSONObject(message);
                                boolean isSuccess=jsonobject.getBoolean("result");
                                if(isSuccess){
                                    //登录成功--暂时保存在对象中
                                    LoginObject loginObject = gson.fromJson(message,LoginObject.class);
                                    String token=loginObject.getMessage();
                                    MyInfo.Token=token;
                                    MyInfo.User_Id=loginObject.getData().getId();
                                    MyInfo.Name=loginObject.getData().getUsername();
                                    MyInfo.Avatar=loginObject.getData().getAvatar();
                                    MyInfo.Phone=loginObject.getData().getPhone();
                                    //保存部分用户信息到本地
                                    SharedPreferences sharedPreferences=context.getSharedPreferences(MyInfo.User_info,0);
                                    SharedPreferences.Editor editor=sharedPreferences.edit();
                                    editor.putInt("user_id",loginObject.getData().getId());
                                    // editor.putString("head_image",Constants.SERVICE_IP+loginAccept.getMessage().getAvatar());
                                    editor.putString("name",loginObject.getData().getUsername());
                                    editor.putString("phone",loginObject.getData().getPhone());
                                    editor.putString("token",token);
                                    editor.putInt("avatar",loginObject.getData().getAvatar());
                                    editor.commit();
                                    MyMethod.toActivity(context, HomePage.class);
                                    ((Activity)context).finish();
                                }else{
                                    MyMethod.ShowDialog(context,jsonobject.getString("message"));
                                }
                            } catch (JSONException e) {
                                MyMethod.showToast(context,message);
                            }
                        }
                    }
                });
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context=getActivity();
    }


  /*  *//**
     * 腾讯实现登录的回调的接口
     *//*
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            if (null == o) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            try {
                int ret = jo.getInt("ret");
                if (0 == ret) {
                    openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                    getUserInfo();
                }
                //Log.i("WXEntry", "腾讯成功返回的接口" + o.toString());
                //登录成功后的跳转
              // MyMethod.toJumpActivity(context,);
            } catch (Exception e) {

            }

        }

        @Override
        public void onError(UiError uiError) {
            //Log.i("WXEntry", "腾讯成功返回的接口错误信息" + uiError.errorMessage + "错误码:" + uiError.errorCode + " 详细错误" + uiError.errorDetail);
        }

        @Override
        public void onCancel() {
            //Log.i("WXEntry", "腾讯接口返回取消");
        }
    }
    public void getUserInfo() {
        UserInfo info = new UserInfo(context, mTencent.getQQToken());
        info.getUserInfo(userInfoListener);
    }
    *//**
     * 获取用户信息监听器
     *//*
    IUiListener userInfoListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            if (o == null) {
                return;
            }
            try {
                JSONObject jo = (JSONObject) o;
                int ret = jo.getInt("ret");
                Log.i("WXEntry", "此时的ret" + ret);
                if (0 == ret) {
                    String nickName = jo.getString("nickname");
                    String gender = jo.getString("gender");
                    String headImage = jo.getString("figureurl_qq_1");
                    bundle.putString("name", nickName);
                    bundle.putString("headImage", headImage);
                    bundle.putString("sex", gender);
                    bundle.putString("unionid", openID);
                    QQTLoginPost(openID);//用获得的QQopenID登录App
                }

            } catch (Exception e) {
            }
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    };
    *//**
     * QQ三方登陆App
     *//*
    private void QQTLoginPost(String openID) {
    }*/
}
